package ch20;
/**
 * You have a large text file containing words. 
 * Given any two words, find the shortest distance (in terms of number of words) 
 * between them in the file. Can you make the searching operation in O(1) time? 
 * What about the space complexity for your solution?
 * 
 * @author Ray
 *
 */
public class ch20_5 {
	
	public static int findshort(String[] words, String word1, String word2){
		int pos = 0;
		int min = Integer.MAX_VALUE /2;
		int pos1 = -min;
		int pos2 = -min;
		for(int i=0;i<words.length;++i){
			String cur_word = words[i];
			if(cur_word.equals(word1)){
				pos1 = pos;
				int dist = pos1-pos2;
				if(dist<min){
					min=dist;
				}
			}
			else if(cur_word.equals(word2)){
				pos2 = pos;
				int dist = pos2-pos1;
				if(dist<min){
					min=dist;
				}
			}
			++pos;
		}
		return min;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String[] words = {"a","bc","d","e","f","a","a","d","e","bc"};
		System.out.println(findshort(words, "a", "f"));
		
	}

}
